package com.lifeonwalden.completionsuggester.support.impl;

import com.lifeonwalden.completionsuggester.support.SuggestFieldFetcher;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SuggestFieldBeanFetcher<T> implements SuggestFieldFetcher<T> {
    private Map<String, Method> methodMap = new HashMap<>();

    public SuggestFieldBeanFetcher(Class<?> clazz, List<String> filedList) {
        try {
            for (String field : filedList) {
                methodMap.put(field, clazz.getDeclaredMethod("get".concat(capitalize(field))));
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String fetch(T item, String field) {
        try {
            return String.valueOf(methodMap.get(field).invoke(item));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String capitalize(String name) {
        if (name != null && name.length() != 0) {
            char[] chars = name.toCharArray();
            chars[0] = Character.toUpperCase(chars[0]);
            return new String(chars);
        } else {
            return name;
        }
    }
}
